#include "item-group-model.h"
#include "tray-items-model.h"

#include <QAbstractItemModel>
#include <QDebug>

ItemGroupModel::ItemGroupModel(QObject *parent) : QSortFilterProxyModel(parent)
{
    QSortFilterProxyModel::setSourceModel(TrayItemsModel::instance());
    m_sourceModel = TrayItemsModel::instance();
    setFilterRole(TrayItemsModel::Row);
    connect(m_sourceModel, &TrayItemsModel::separateIndexChanged, this, [this](){
        invalidateFilter();
    });
}

void ItemGroupModel::setModelType(GroupType type)
{
    m_groupType = type;
}

ItemGroupModel::GroupType ItemGroupModel::getModelType()
{
    return m_groupType;
}

void ItemGroupModel::onActivate(const QModelIndex &index)
{
    m_sourceModel->activate(mapToSource(index));
}

void ItemGroupModel::onContextMenu(const QModelIndex &index)
{
    m_sourceModel->showContextMenu(mapToSource(index));
}

QVariant ItemGroupModel::data(const QModelIndex &index, int role) const
{
    return sourceModel()->data(mapToSource(index), role);
}

QVariant ItemGroupModel::foldIcon()
{
    return QIcon::fromTheme("ukui-end.symbolic");
}

int ItemGroupModel::groupBegin() const
{
    if (m_groupType == GroupType::Show) {
        return 0;
    } else if (m_groupType == GroupType::Fold) {
        return m_sourceModel->getSeparateIndex() + 1;
    }
}

int ItemGroupModel::groupEnd() const
{
    if (m_groupType == GroupType::Show) {
        return m_sourceModel->getSeparateIndex();
    } else if (m_groupType == GroupType::Fold) {
        return m_sourceModel->rowCount(QModelIndex()) - 1;
    }
}

bool ItemGroupModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    if (m_groupType == GroupType::Show) {
        return source_row >= 0 && source_row <= m_sourceModel->getSeparateIndex();
    } else if (m_groupType == GroupType::Fold) {
        return source_row > m_sourceModel->getSeparateIndex() && source_row <= (m_sourceModel->rowCount(QModelIndex()) - 1);
    }
    return true;
}

